package net.vsspl.portal.restlet;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.logging.Logger;

import net.vsspl.portal.ds.model.Session;

import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class GetSessionData extends ServerResource {
	Logger log = Logger.getLogger(GetSessionData.class.getName());
	@Post
	public Representation getSessionData(Representation r) throws IOException{
		Form responseHeaders = (Form) getResponse().getAttributes().get("org.restlet.http.headers");
		if (responseHeaders == null) {
			responseHeaders = new Form();
			getResponse().getAttributes().put("org.restlet.http.headers",responseHeaders);
		}
		responseHeaders.add("Access-Control-Allow-Origin", "*");
		DomRepresentation dom = new DomRepresentation(MediaType.TEXT_XML);
		Document document = dom.getDocument();
		Element e = document.createElement("SessionData");
		document.appendChild(e);
		try {
			Form f = new Form(r);
			System.out.println("getting form data");
			
			String sessionId = f.getFirstValue("sessionID");
			log.warning(sessionId);
			Session session = Session.getSessionData(sessionId);
			ByteArrayInputStream bys = new ByteArrayInputStream(session.getValue());
		
			ObjectInput objectInput = new  ObjectInputStream(bys);
			HashMap<Object, Object> map = (HashMap<Object, Object>) objectInput.readObject();
			log.warning(map.size()+"");
			Iterator<Entry<Object, Object>> iterator =  map.entrySet().iterator();
			
			while (iterator.hasNext()) {
				Entry<Object, Object> entry = (Entry<Object, Object>) iterator.next();
				log.warning(entry.getKey().toString()+"  "+entry.getValue().toString());
				Element e1 = document.createElement(entry.getKey().toString());
				e1.appendChild(document.createTextNode(entry.getValue().toString()));
				e.appendChild(e1);
			}
			document.normalize();
			return dom;
		} catch (Exception exe) {
			log.warning(exe.toString());
			exe.printStackTrace();
		}
		
		return dom;
		
	}

}
